package com.gxuwz.attend.web.servlet;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Department;
import com.gxuwz.attend.service.Impl.DepartmentServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name="departmentServlet",urlPatterns = "/dep")
public class DepartmentServlet extends BaseHttpServlet{
    private final Logger logger= LoggerFactory.getLogger(DepartmentServlet.class);
    private final static String VIEW_ADD="/WEB-INF/views/dep/dep_add.jsp";
    private final static String VIEW_EDIT="/WEB-INF/views/dep/dep_edit.jsp";
    private final static String VIEW_LIST="/WEB-INF/views/dep/dep_list.jsp";
    private final static String ACTION_LIST="/dep?action=list";
    private DepartmentServiceImpl departmentService;

    @Override
    public void init() throws ServletException {
        super.init();
        departmentService = AppContext.getBean(DepartmentServiceImpl.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("..................");
        System.out.println();
        //1：接受请求参数action以及其他页面的参数值，按照约定，动作请求action依次为input、add、delete、get、edit、list.
        String action =req.getParameter("action");
        System.out.println("action:" + action);
        String view=ErrorPage_500;
        logger.info("request process starting"+action);
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "input":
                    view = VIEW_ADD;
                    Department dep=new Department();
                    dep.setDepID("");
                    dep.setDepName("");
                    req.setAttribute("dep",dep);
                    break;
                case "add":
                    dep = new Department();
                    resolveRequestParameter(req,dep);
                    System.out.println("添加数据："+dep);
                    departmentService.insertDep(dep);
                    dep.setDepID(null);
                    dep.setDepName(null);
                    view = ACTION_LIST;
                    break;
                case "delete":
                    String id =req.getParameter("id");
                    System.out.println("删除id:");
                    departmentService.deleteDep(id);
                    view = ACTION_LIST;
                    break;
                case "get":
                    id =req.getParameter("id");
                    dep=new Department();
                    dep.setDepID(id);
                    List<Department> depList = new ArrayList<>();
                    depList=departmentService.queryDep(dep);
                    dep = depList.get(0);
                    view = VIEW_EDIT;
                    req.setAttribute("m",dep);
                    break;
                case "edit":
                    dep = new Department();
                    resolveRequestParameter(req,dep);
                    System.out.println("edit:"+dep);
                    departmentService.updateDep(dep);
                    dep.setDepID(null);
                    dep.setDepName(null);
                    view = ACTION_LIST;
                    break;
                case "list":
                    System.out.println(11);
                    String depName=req.getParameter("depName11");
                    System.out.println("depName:"+depName);
                    if (depName==null||depName.isEmpty()){
                        System.out.println("//////////////");
                        Department dep3 = new Department();
                        List<Department> depList1 = departmentService.queryDeps();
                        view = VIEW_LIST;
                        System.out.println("depList:"+depList1);
                        req.setAttribute("list",depList1);
                        break;
                    }else{
                        System.out.println("//////////////.....");
                        Department dep4=new Department();
                        dep4.setDepName(depName);
                        List<Department> depList2 = departmentService.queryDep(dep4);
                        view = VIEW_LIST;
                        req.setAttribute("list",depList2);
                        break;
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message",e.getMessage());
            view =ErrorPage_500;
        }
        //3:页面跳转，默认转发方式
        super.doDispatch(req,resp,view);
    }

    /**
     * 解析request参数并转换为POJO对象
     * @param req
     */
    private void resolveRequestParameter(HttpServletRequest req,Object bean){
        Map<String,String[]> reqParameterMap= req.getParameterMap();
        Map<String,String[]> propertiesMap=new HashMap<String,String[]>();
        try {
            for (Map.Entry<String,String[]>  entry : reqParameterMap.entrySet()){
                String name =entry.getKey();
                String[] values=entry.getValue();
                //判断request参数是否对应JavaBean对象的属性
                Class propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType!=null) {
                    propertiesMap.put(name,values);
                }
            }
            //转换为POJO对象bean的属性值
            BeanUtils.populate(bean,propertiesMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("The property name could not be found",e);
        }

    }
}
